/*
 * @Author: szx
 * @Date: 2023-03-27 19:09:13
 * @LastEditTime: 2023-03-29 20:08:18
 * @Description: 
 * @FilePath: \learn\fullstackopen\part1\part1\src\App.js
 */
import { useState, useEffect } from 'react'
import Filter from './components/Filter'
import PersonForm from './components/PersonForm'
import Persons from './components/Persons'
import Notification from './components/Notification'
import { getAll, create, update, remove } from './service/persons'

const App = () => {
  const [persons, setPersons] = useState([])
  const [newName, setNewName] = useState('')
  const [newNumber, setNewNumber] = useState('')
  const [filter, setFilter] = useState('')
  const [notification, setNotification] = useState(null)


  useEffect(() => {
    getAll().then(res => {
      setPersons(res)
    })
  }, []);

  const addPerson = (event) => {
    event.preventDefault();
    const findPerson = persons.find((person) => person.name === newName)
    if (!findPerson) {
      const newPerson = { name: newName, number: newNumber };
      create(newPerson).then((res) => {
        console.log('create', res)
        setPersons(persons.concat(res))
        setNotification({
          type: 'notification',
          text: `${res.name}' creat.`
        })
        setTimeout(() => setNotification(null), 5000)
      }).catch(error => {
        console.log(error)
        setNotification({
          type: 'error',
          text: error.response.data.error
        })
        setTimeout(() => setNotification(null), 5000)
      })

    }
    if (findPerson) {
      if (findPerson.number === newNumber)
        alert(`${newName} is already added to phonebook`)
      else {
        const confirm = window.confirm(`${newName} is already added to phonebook, replace the old number with new one?`);
        if (confirm) {
          update(findPerson.id, { ...findPerson, number: newNumber }).then((res) => {
            console.log(res);
            setPersons(persons.map(person => person.id !== findPerson.id ? person : res))
            setNotification({
              type: 'notification',
              text: `${findPerson.name}'s number was updated.`
            })
            setTimeout(() => setNotification(null), 5000)
          }).catch(error => {
            setPersons(persons
              .filter(person =>
                person.name !== findPerson.name
              )
            )
            setNotification({
              type: 'error',
              text: `${findPerson.name} has already been deleted from the server.`
            })
            setTimeout(() => setNotification(null), 5000)
          }

          )
        }
      }
    }

  }
  const deletePerson = (id) => {
    const person = persons.find(p => p.id === id);
    const confirmDelete = window.confirm(`Delete ${person.name} ?`);

    if (confirmDelete) {
      remove(id).then(
        res => {
          if (res === 200)
            setPersons(persons.filter(person => person.id !== id));
        }
      ).catch(error => {
        setNotification({
          type: 'error',
          text: `Information of ${person.name} has already been deleted from the server.`
        })
        setTimeout(() => setNotification(null), 5000)
      })
    }

  }

  const handleNameChange = (event) => {
    setNewName(event.target.value)
  }
  const handleNumberChange = (event) => {
    setNewNumber(event.target.value)
  }
  const handleFilterChange = (event) => {
    setFilter(event.target.value)
  }
  const filterPerson = filter === '' ? persons : persons.filter((person) =>
    person.name.toLowerCase().startsWith(filter.toLowerCase())
  )

  return (
    <div>
      <h2>Phonebook</h2>
      <Notification notification={notification} />

      <Filter filter={filter} handleFilter={handleFilterChange} />

      <h3>Add a new</h3>
      <PersonForm addPerson={addPerson} newName={newName} handleNameChange={handleNameChange} newNumber={newNumber} handleNumberChange={handleNumberChange} />

      <h3>Numbers</h3>
      <Persons persons={filterPerson} deletePerson={deletePerson} />
    </div>
  )
}

export default App